# coding=utf-8

"""
    Created by Kalyter on 2018-03-18.
"""
import os

import re

from learning.scientifc import writer
from learning.scientifc.jobs.job import Job
from learning.scientifc.readers.reader import ReaderFactory


class JudgeSubCategory(Job):
    name = '计算子分类对应的 xml 文件下是否存在对应子分类名称'

    def __init__(self, app):
        super().__init__(app)
        self.feature_file = self.app.config.get('S_C_FEATURES_FILE')
        self.xml_path = self.app.config.get('S_C_XML_PATH')
        self.factory = ReaderFactory(app)
        self.name_pattern = re.compile(r'.*<name>(.*)</name>')
        self.investment_pattern = re.compile(r'.*<chapter.*?name="Investment".*?>(.*?)</chapter>.*')
        self.sub_category_column = self.app.config.get('S_C_COLUMN')

    def run(self):
        # 1. 读取 xml 文件夹下的所有文件，获取所有文件的 name 标签字段，
        #    以及 chapter 当中 name 为 Investment 的字段
        # 2. 读取 feature 文件，循环其中的 sub-category 字段，
        #    在 investments 列表中查找，默认值都为 0 ，找到的对应值更新为 1；
        self.logger.info('第一步：开始初始化数据')
        reader = self.factory.create(self.feature_file)
        names = []
        investments = []

        self.logger.info('第二步：读取 names 和 investments 列表')
        files = os.listdir(self.xml_path)
        for name in files:
            filename = os.path.join(self.xml_path, name)
            if os.path.isfile(filename):
                with open(filename, encoding='utf-8') as f:
                    content = f.read().strip().replace('\n', '')
                    match = self.name_pattern.match(content)
                    names.append(match.group(1) if match else '')

                    match = self.investment_pattern.match(content)
                    investments.append(match.group(1) if match else '')

        self.logger.info('第三步：判断 investment 字段中是否存在对应的子类目')
        header = reader.row_values(0)
        sub_category_index = header.index(self.sub_category_column)

        write_header = tuple(header[:2] + names)
        write_data = [write_header]

        for i, row in reader.range(1):
            data = []
            data += row[:2]
            sub_category = row[sub_category_index]
            for investment, name in zip(investments, names):
                if sub_category in investment:
                    data.append(1)
                else:
                    data.append(0)
            write_data.append(tuple(data))

        self.logger.info('第四步：开始写入文件')

        writer.write(write_data)
